using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MediatR;
using RBAC.Domain.Dto.Output;
using RBAC.ErrorCode;
using RBAC.Write.Api.Application.Command.ERP.InboundManagement;
using RBAC.Write.Api.Application.Dto.ERP;

namespace RBAC.Write.Api.Controllers.ERP
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class InboundManagementController : ControllerBase
    {
        private readonly IMediator _mediator;

        public InboundManagementController(IMediator mediator)
        {
            _mediator = mediator;
        }

        /// <summary>
        /// 新增采购入库（含明细）
        /// </summary>
        [HttpPost]
        public async Task<APIResult<long>> AddPurchaseStorage([FromBody] AddPurchaseStorageCommand request, CancellationToken cancellationToken)
        {
            try
            {
                return await _mediator.Send(request, cancellationToken);
            }
            catch (Exception ex)
            {
                return new APIResult<long>
                {
                    Code = APIEnums.Error,
                    Msg = $"新增采购入库失败: {ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 编辑采购入库（含明细：先删后增）
        /// </summary>
        [HttpPost]
        public async Task<APIResult<bool>> UpdatePurchaseStorage([FromBody] UpdatePurchaseStorageCommand request, CancellationToken cancellationToken)
        {
            try
            {
                return await _mediator.Send(request, cancellationToken);
            }
            catch (Exception ex)
            {
                return new APIResult<bool>
                {
                    Code = APIEnums.Error,
                    Msg = $"编辑采购入库失败: {ex.Message}",
                    Data = false
                };
            }
        }

        /// <summary>
        /// 删除采购入库（逻辑删除：主表与明细 IsDeleted=1）
        /// </summary>
        [HttpPost]
        public async Task<APIResult<bool>> DeletePurchaseStorage([FromBody] DeletePurchaseStorageCommand request, CancellationToken cancellationToken)
        {
            try
            {
                return await _mediator.Send(request, cancellationToken);
            }
            catch (Exception ex)
            {
                return new APIResult<bool>
                {
                    Code = APIEnums.Error,
                    Msg = $"删除采购入库失败: {ex.Message}",
                    Data = false
                };
            }
        }

        /// <summary>
        /// 审批/反审采购入库（传 TargetStatus=开立/审批）
        /// </summary>
        [HttpPost]
        public async Task<APIResult<bool>> AppOrUnappPurchaseStorage([FromBody] AppOrUnappPurchaseStorageCommand request, CancellationToken cancellationToken)
        {
            try
            {
                return await _mediator.Send(request, cancellationToken);
            }
            catch (Exception ex)
            {
                return new APIResult<bool>
                {
                    Code = APIEnums.Error,
                    Msg = $"审批/反审失败: {ex.Message}",
                    Data = false
                };
            }
        }

        /// <summary>
        /// 导出采购入库
        /// </summary>
        /// <param name="request">导出请求参数</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>Excel文件</returns>
        [HttpGet]
        public async Task<IActionResult> ExportPurchaseStorage([FromQuery] ExportPurchaseStorageCommand request, CancellationToken cancellationToken)
        {
            var result = await _mediator.Send(request, cancellationToken);
            if (result.Code != APIEnums.Success)
            {
                return BadRequest(result);
            }

            return File(
                result.Data,
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                $"采购入库导出_{DateTime.Now:yyyyMMddHHmmss}.xlsx"
            );
        }
    }
}
